const fs=require('fs');
const request=require('request-promise');
const {spawn}=require('child_process');
const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function init(){
    if (fs.existsSync('./chong.ts'))
    {
        fs.unlinkSync('./chong.ts');
    }

    if (fs.existsSync('./filelist.txt'))
    {
        fs.unlinkSync('./filelist.txt');
    }

    let mutxt=fs.readFileSync('./m3u8','utf-8');
    let txtArr=mutxt.split('\r\n');
    let index=0;
    
    let klist=[];
    for (let item of txtArr){
        if (item.substring(0,4)==='http'){
            klist.push(item);
        }
    }
    console.log(`共${klist.length}块`);
    
    for (let item of klist){
        let buf=await request({
            url:item,
            encoding:null
        }).catch((e)=>{
            console.log(e);
        })
        
        fs.writeFileSync(`./chong.ts`,buf,{
            flag:'a'
        })
        index++;
        console.log(`合并${index}块`);
    }
    
}

const margeTs=()=>{
    return new Promise((resolve,reject)=>{
        const exe=spawn('ffmpeg.exe',['-f','concat','-i','filelist.txt','-c','copy','chong.ts']);
        
        exe.on('close',(code)=>{
            resolve(code)
        })
    })
}

init();
